<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="icon" type="image/png" sizes="16x16" href="./logo_64x64.ico">
    <title>高中英语测试卷</title>
    <script src="exam/tailwindcss.min.js"></script>
    <script src="exam/exam.js"></script>
    <script src="exam/content.js"></script>
    <script src="exam/senior.js"></script>
    <script src="exam/showCorrect.js"></script>
    <!-- 引入Font Awesome图标 -->
    <link rel="stylesheet" href="exam/fontawesome.css">
    <link rel="stylesheet" href="exam/pop.css">
    <link rel="stylesheet" href="exam/select.css">
    <!-- 配置Tailwind自定义颜色和字体 -->
    <script>
        tailwind.config = {
            theme: {
                extend: {
                    colors: {
                        primary: '#3b82f6',
                        secondary: '#64748b',
                        accent: '#f97316',
                        neutral: '#f1f5f9',
                        success: '#10b981',
                        danger: '#ef4444',
                    },
                    fontFamily: {
                        sans: ['Inter', 'system-ui', 'sans-serif'],
                        serif: ['Georgia', 'serif'],
                    },
                },
            }
        }
    </script>

    <style type="text/tailwindcss">

        @layer utilities {
            .btn-primary {
                @apply bg-primary text-white px-6 py-2 rounded-md hover:bg-primary/90 transition-all duration-200 focus:ring-2 focus:ring-primary/50 focus:outline-none;
            }

            .btn-secondary {
                @apply bg-white text-gray-700 border border-gray-300 px-6 py-2 rounded-md hover:bg-gray-50 transition-all duration-200;
            }

            .section-title {
                @apply text-xl font-bold text-gray-800 mb-4 pb-2 border-b border-gray-200;
            }

            .option-selected {
                @apply border-primary bg-primary/5 ring-1 ring-primary;
            }
        }

        h1, h2, h3, h4, h5, h6 {
            @apply text-center;
        }

        .option {
            transition: all 0.2s ease;
            cursor: pointer;
        }
        .option:hover {
            background-color: #f1f5f9;
        }
        .option.selected {
            background-color: #dbeafe;
            border-color: #3b82f6;
        }
        .option.correct {
            background-color: #dcfce7;
            border-color: #10b981;
        }
        .option.incorrect {
            background-color: #fee2e2;
            border-color: #ef4444;
        }

        /* 内层容器：限制宽度并居中，使h标签整体居中显示 */
        .centered-container {
            max-width: 700px; /* 限制内容宽度 */
            margin-left: auto;
            margin-top: 1.0rem;
            margin-right: auto; /* 左右margin自动实现容器居中 */
        }

        /* 子元素样式-居中 */
        .child-element {
            height: 40px;
            padding: 1rem;
            border-radius: 0.375rem;
            text-align: center;
        }

        /* 2. Grid 居中 */
        .grid-center {
            display: grid;
            place-items: center; /* 同时实现水平和垂直居中 */
        }

        /* 基础居左样式 */
        .span-left {
            background-color: #dbeafe;
            color: #1e40af;
            padding: 0 0.25rem;
        }

        .two-columns {
            column-count: 3;      /* 分为列 */
            column-gap: 2rem;     /* 列之间的间距 */
            text-align: center;   /* 文字居中 */
        }
    </style>
</head>
<body class="bg-gray-50 font-sans text-gray-800">
<header class="bg-white shadow-sm sticky top-0 z-50">
    <div class="container mx-auto px-4 py-3 flex flex-col md:flex-row justify-between items-center">
        <div class="flex items-center">
            <a href="#" class="flex items-center">
                <img src="./img/exam-logo.png" alt="网站Logo" style="width: 300px;height: 80px"
                     class="h-10 w-full rounded-full object-cover">
                <span class="ml-3 text-xl font-bold text-gray-800"></span>
            </a>
        </div>

        <div class="flex items-center mb-3 md:mb-0">
            <h1 class="text-lg md:text-xl font-bold">高中英语测试卷</h1>
        </div>

        <div class="flex items-center w-full md:w-auto justify-between">
            <div class="flex items-center mr-4">
                <i class="fa fa-clock-o text-accent mr-2"></i>
                <span id="timer" class="font-mono text-accent">35:00</span>
            </div>

            <div id="submitBtn" class="popup-container">
                <div class="trigger bg-blue-500 text-white px-4 py-2 rounded-full">
                    <i class="fa fa-paper-plane mr-2"></i>
                    交卷
                </div>
            </div>

            <div class="popup-container-hidden ml-2" onclick='showCorrectAnswer(false)'>
                <div class="trigger bg-green-500 text-white px-4 py-2 rounded-full">
                    <i class="fa fa-book-atlas mr-2"></i>
                    检查
                </div>
                <div class="popup popup-bottom">
                    <h3 class="font-medium text-gray-800 mb-1">操作提示</h3>
                    <p class="text-sm text-gray-600">操作将检查已经完成的,对的将标识✅</p>
                </div>
            </div>

            <div class="popup-container-hidden ml-2" onclick='showCorrectAnswer(true)'>
                <div class="trigger bg-purple-500 text-white px-4 py-2 rounded-full">
                    <i class="fa fa-map mr-2"></i>
                    判卷
                </div>
                <div class="popup popup-bottom">
                    <h3 class="font-medium text-gray-800 mb-1">操作提示</h3>
                    <p class="text-sm text-gray-600">操作将检查已经完成的,标识 和 ❌ </p>
                </div>
            </div>

            <div style="display: none" class="popup-container ml-2" onclick='test()'>
                <div class="trigger bg-purple-500 text-white px-4 py-2 rounded-full">
                    <i class="fa fa-map mr-2"></i>
                    临时
                </div>
            </div>
        </div>
    </div>
</header>

<main class="container mx-auto px-4 py-6">
    <!-- 试卷信息 -->
    <div class="bg-white rounded-lg shadow-sm border border-gray-200 p-5 mb-8">
        <div class="flex flex-col md:flex-row justify-between items-start md:items-center mb-4">
            <div>
                <p class="text-gray-600">考试时间：35分钟</p>
            </div>
            <div class="mt-4 md:mt-0 flex flex-col items-end">
                <p>姓名：
                    <input type="text"
                           id="name"
                           placeholder="请输入姓名"
                           class="border border-gray-300 rounded px-2 py-1 mt-1">
                </p>
                <p class="mt-2">校区：
                    <input type="text"
                           id="campus"
                           placeholder="请输入校区"
                           class="border border-gray-300 rounded px-2 py-1 mt-1">
                </p>
            </div>
        </div>

        <div class="bg-blue-50 p-4 rounded-md border border-blue-100">
            <h2>
                Dear Learners
            </h2>
            <h3 class="font-bold text-primary flex">
                Warm Welcome to DONGS Overseas Academy!
            </h3>
            <p>
                We are delighted to extend a warm welcome to you as you embark on your journey of learning courses
                at our esteemed academy. At DONGS, we are committed to providing a supportive and enriching learning
                environment that will empower you to achieve your goals and excel in your endeavors.
            </p>
            <p>
                我们很高兴热烈欢迎您到董氏留学学习课程。在董氏，我们致力于提供一个支持性和丰富的学习环境，
                使您能够实现自己的目标并在相应考试中取得优异成绩。
            </p>
        </div>

        <div class="bg-blue-50 p-4 mt-5 rounded-md border border-blue-100">
            <ul class="list-disc list-inside mt-2 text-gray-700 text-sm space-y-1">
                <li>请在规定时间内完成所有题目并提交</li>
                <li>点击选项即可选择答案，可随时修改</li>
                <li>请确保网络连接稳定</li>
            </ul>
        </div>
    </div>

    <!-- 第一部分-词汇 -->
    <section class="mb-10">
        <h3 class="section-title flex items-center">
            <i class="fa fa-book text-primary mr-2"></i>
            词汇:
        </h3>

        <div class="bg-white mt-5 rounded-lg shadow-sm p-4 mb-6">
            <div class="flex flex-col md:flex-row justify-between items-start md:items-center">
                <div>
                    <p>
                        写出下列单词的汉语意思
                    </p>
                </div>
            </div>
        </div>

        <div class="flex flex-col lg:flex-row gap-6">
            <div class="lg:w-1/2 bg-card rounded-lg shadow-sm border border-gray-200 overflow-hidden">
                <div class="bg-gray-50 px-4 py-3 border-b border-gray-200 font-medium">
                    <i class="fa fa-file-text text-primary mr-2"></i>内容
                </div>
                <div id="wordArrayContainer" class="two-columns p-5 overflow-y-auto scrollbar-thin">

                </div>
            </div>

            <div class="lg:w-1/2 bg-card rounded-lg shadow-sm border border-gray-200 overflow-hidden">
                <div class="bg-gray-50 px-4 py-3 border-b border-gray-200 font-medium flex justify-between ">
                    <div class="flex items-center">
                        <i class="fa fa-list-alt text-primary mr-2"></i>
                        Answer答案：
                    </div>
                </div>

                <div id="wordArraySelectContainer" class="two-columns p-5 overflow-y-auto scrollbar-thin">

                </div>
            </div>
        </div>

        <div class="bg-white mt-5 rounded-lg shadow-sm p-4 mb-6">
            <div class="flex flex-col md:flex-row justify-between items-start md:items-center">
                <div>
                    <p>
                        请写出如下单词的延伸词
                    </p>
                </div>
            </div>
        </div>

        <div class="flex flex-col lg:flex-row gap-6">
            <div class="lg:w-1/6 bg-card rounded-lg shadow-sm border border-gray-200 overflow-hidden">
                <div class="bg-gray-50 px-4 py-3 border-b border-gray-200 font-medium">
                    <i class="fa fa-file-text text-primary mr-2"></i>内容
                </div>
                <div id="wordExpandContainer" class="p-5 overflow-y-auto scrollbar-thin">

                </div>
            </div>

            <div class="lg:w-5/6 bg-card rounded-lg shadow-sm border border-gray-200 overflow-hidden">
                <div class="bg-gray-50 px-4 py-3 border-b border-gray-200 font-medium flex justify-between">
                    <div class="flex items-center">
                        <i class="fa fa-list-alt text-primary mr-2"></i>
                        Answer答案：
                    </div>
                </div>

                <div id="wordExpandAnswerContainer" class="p-5 overflow-y-auto scrollbar-thin">

                </div>
            </div>
        </div>

        <div class="bg-white mt-5 rounded-lg shadow-sm p-4 mb-6">
            <div class="flex flex-col md:flex-row justify-between items-start md:items-center">
                <div>
                    <p>
                        按要求完成下列问题
                    </p>
                </div>
            </div>
        </div>

        <div class="flex flex-col lg:flex-row">
            <div class="w-full bg-white rounded-xl shadow-md p-6 md:p-8">
                <div class="flex items-start mb-4">
                    <div class="flex-shrink-0 rounded-full flex items-center justify-center text-blue-600 font-bold"></div>
                    <h6 id="grammarDemandContainer" class="text-xm text-gray-800"></h6>
                </div>

                <div class="ml-1">
                    <label id="question_text1" for="answer1" class="block text-sm font-medium text-gray-700 mb-2"></label>
                    <textarea id="answer1" name="answer1" class="answer-textarea w-full px-4 py-3 border border-gray-300
                     rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-blue-500 transition duration-200"
                              placeholder="请在此输入你的答案..."></textarea>
                </div>

                <div class="ml-1 mt-2">
                    <label id="question_text2" for="answer2" class="block text-sm font-medium text-gray-700 mb-2"></label>
                    <textarea id="answer2" name="answer2" class="answer-textarea w-full px-4 py-3 border border-gray-300
                     rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-blue-500 transition duration-200"
                              placeholder="请在此输入你的答案..."></textarea>
                </div>
            </div>
        </div>
    </section>

    <!-- 第二部分-语法 -->
    <section class="mb-10">
        <h3 class="section-title flex items-center">
            <i class="fa fa-pencil text-primary mr-2"></i>
            语法:
        </h3>
        <div class="flex flex-col mt-5 lg:flex-row gap-6">
            <div class="lg:w-3/4 bg-white rounded-lg shadow-sm border border-gray-200 overflow-hidden">
                <div class="bg-gray-50 px-4 py-3 border-b border-gray-200 font-medium flex items-center">
                    <i class="fa fa-sharp-duotone fa-light fa-book text-primary mr-2"></i>
                    语法填空
                </div>
                <div class=" p-6 overflow-y-auto scrollbar-custom">
                    <div id="grammarInputContainer" class="text-gray-700 font-medium pt-1 leading-relaxed space-y-4">

                    </div>
                </div>
            </div>

            <div class="lg:w-1/4 bg-white rounded-lg shadow-sm border border-gray-200 overflow-hidden">
                <div class="bg-gray-50 px-4 py-3 border-b border-gray-200 font-medium flex justify-between items-center">
                    <div class="flex items-center">
                        <i class="fa fa-list-alt text-primary mr-2"></i>Answer答案：
                    </div>
                </div>
                <div class=" p-6 overflow-y-auto scrollbar-custom">
                    <div id="grammarInputAnswerContainer" class="space-y-15">

                    </div>
                </div>
            </div>
        </div>

    </section>

    <!-- 第四部分-阅读 -->
    <section class="mb-10">
        <h3 class="section-title flex items-center">
            <i class="fa fa-file-text text-primary mr-2"></i>
            阅读：
        </h3>

        <div class="flex flex-col mb-5 lg:flex-row gap-6">
            <div class="lg:w-1/2 bg-white rounded-lg shadow-sm border overflow-hidden">
                <div id="readingInputContainer" class="px-4 pt-3">

                </div>
            </div>

            <div class="lg:w-1/2 bg-white rounded-lg shadow-sm border border-gray-200 overflow-hidden">
                <div class="md:flex-row items-start mt-3">
                    <div id="readingInputAnswerContainer" class="gap-3 pl-5 pr-5">

                    </div>
                </div>
            </div>
        </div>
    </section>

    <!-- 第五部分-写作-->
    <section class="mb-10">
        <h3 class="section-title flex items-center">
            <i class="fa fa-pencil text-primary mr-2"></i>
            写作：
        </h3>

        <div class="flex flex-col lg:flex-row gap-6">
            <div class="lg:w-1/2 bg-card rounded-lg shadow-sm border border-gray-200 overflow-hidden">
                <div class="bg-gray-50 px-4 py-3 border-b border-gray-200 font-medium">
                    <i class="fa fa-file-text text-primary mr-2"></i>
                    阅读下面材料，根据其内容和所给段落开头语续写两段，使之构成一篇完整的短文。
                </div>
                <div id="articleInputContainer" class="p-5  overflow-y-auto scrollbar-thin">

                </div>
            </div>

            <div class="lg:w-1/2 bg-card rounded-lg shadow-sm border border-gray-200 overflow-hidden">
                <div class="bg-gray-50 px-4 py-3 border-b border-gray-200 font-medium flex justify-between ">
                    <div class="flex items-center">
                        <i class="fa fa-list-alt text-primary mr-2"></i>
                        Answer答案：
                    </div>
                </div>
                <div class="p-5 overflow-y-auto scrollbar-thin">
                    <div class="space-y-6">
                        <textarea
                                id="article"
                                class="w-full h-hull px-4 py-2 border border-gray-300 rounded-lg resize-none"
                                cols="100" rows="19" placeholder="请输入..."></textarea>
                    </div>
                </div>
            </div>
        </div>
    </section>
</main>

<!-- 页脚 -->
<footer class="bg-white border-t border-gray-200 py-4 mt-10">
    <div class="container mx-auto px-4 text-center text-gray-600 text-sm">
        <p>技术支持:董氏留学 | 高中英语测试卷 | 请勿在考试期间刷新页面或关闭浏览器</p>
    </div>
</footer>

<!-- 交卷确认模态框 -->
<div id="submitModal" class="fixed inset-0 bg-black/50 flex items-center justify-center z-50 hidden">
    <div class="bg-white rounded-lg shadow-lg w-full max-w-md p-6 transform transition-all">
        <div class="text-center mb-4">
            <div class="inline-flex items-center justify-center w-16 h-16 rounded-full bg-yellow-100 text-accent mb-4">
                <i class="fa fa-exclamation-triangle text-2xl"></i>
            </div>
            <h3 class="text-xl font-bold text-gray-800">确认交卷？</h3>
            <p class="text-gray-600 mt-2">您确定要提交试卷吗？提交后将无法修改答案。</p>
            <div class="mt-6 flex gap-3">
                <button id="cancelSubmit" class="flex-1 btn-secondary">取消</button>
                <button id="confirmSubmit" class="flex-1 btn-primary">确认交卷</button>
            </div>
        </div>
    </div>
</div>

<!-- 提交成功模态框 -->
<div id="successModal" class="fixed inset-0 bg-black/50 flex items-center justify-center z-50 hidden">
    <div class="bg-white rounded-lg shadow-lg w-full max-w-md p-6 transform transition-all">
        <div class="text-center mb-4">
            <div class="inline-flex items-center justify-center w-16 h-16 rounded-full bg-green-100 text-success mb-4">
                <i class="fa fa-check text-2xl"></i>
            </div>
            <h3 class="text-xl font-bold text-gray-800">提交成功</h3>
            <p id="submitData5" class="text-left text-gray-600 mt-2">词汇:正确率: 0 %</p>
            <p id="submitData1" class="text-left text-gray-600 mt-2">语法-语句:正确率: 0 %</p>
            <p id="submitData6" class="text-left text-gray-600 mt-2">语法-单词:正确率: 0 %</p>
            <p id="submitData2" class="text-left text-gray-600 mt-2">听力-短文:正确率: 0 %</p>
            <p id="submitData7" class="text-left text-gray-600 mt-2">听力-选择:正确率: 0 %</p>
            <p id="submitData4" class="text-left text-gray-600 mt-2">听力-单词:正确率: 0 %</p>
            <p id="submitData3" class="text-left text-gray-600 mt-2">阅读:正确率: 0 %</p>
            <p class="text-left text-gray-600 mt-2">写作:<span style="color: red">等待老师评分</span></p>
            <p class="text-gray-600 mt-2">感谢您的参与！</p>
            <div class="mt-6">
                <button id="closeSuccess" class="w-full btn-primary">关闭</button>
            </div>
        </div>
    </div>
</div>

<script>
    let userData = {
        list: []
    };

    let selectQuestionValueList = [];
    const grammarWordShuffle = shuffleArray(grammarWordContext)

    // 获取卡片容器
    const wordArrayContainer = document.getElementById('wordArrayContainer');
    const wordArraySelectContainer = document.getElementById('wordArraySelectContainer');

    const wordExpandContainer = document.getElementById('wordExpandContainer');
    const wordExpandAnswerContainer = document.getElementById('wordExpandAnswerContainer');

    const grammarInputContainer = document.getElementById('grammarInputContainer');
    const grammarDemandContainer = document.getElementById('grammarDemandContainer');
    const grammarInputAnswerContainer = document.getElementById('grammarInputAnswerContainer');

    const articleInputContainer = document.getElementById('articleInputContainer');

    const readingInputContainer = document.getElementById('readingInputContainer');
    const readingInputAnswerContainer = document.getElementById('readingInputAnswerContainer');

    userAnswers = []
    grammarSelectAnswers = {}
    userAnswersSelect = {}
    userReadingSelect = {}

    //词汇-单词翻译-初始化
    function wordTranslateInit() {
        wordArrayContainer.innerText = ''
        let questionIndex = 1
        let cardData = shuffleArray(wordArray);
        cardData.forEach((word) => {
            // console.log(word)
            const inputWrapper = document.createElement('p');
            const spanWrapper = document.createElement('span');
            const spanRightWrapper = document.createElement('span');
            inputWrapper.className = 'flex relative items-center gap-3 mb-3';
            spanWrapper.textContent = questionIndex + '.';
            spanRightWrapper.textContent = word
            spanWrapper.className = 'span-left'
            questionIndex++
            inputWrapper.appendChild(spanWrapper);
            inputWrapper.appendChild(spanRightWrapper);
            wordArrayContainer.appendChild(inputWrapper);
        })
        // console.log(wordArrayContainer)
    }

    //词汇-单词翻译-初始化-回答
    function wordTranslateAnswerInit() {
        wordArraySelectContainer.innerText = ''
        let questionIndex = 1
        wordArray.forEach(() => {
            const inputContainer = document.createElement('div');
            inputContainer.className = 'flex mb-3 relative items-center gap-3';

            const inputWrapper = document.createElement('input');
            const spanWrapper = document.createElement('span');
            spanWrapper.className = 'w-6 text-center font-medium span-left'; // 固定宽度，居中对齐
            spanWrapper.textContent = `${questionIndex}.`;

            inputWrapper.placeholder = `请输入第 ${questionIndex} 个`; // 提示文本
            inputWrapper.className = 'border border-gray-300 rounded-md ';
            questionIndex++
            inputContainer.appendChild(spanWrapper);
            inputContainer.appendChild(inputWrapper);
            wordArraySelectContainer.appendChild(inputContainer);
        })
        // console.log(wordArrayContainer)
    }

    //词汇-单词扩展-初始化
    function wordExpandInit() {
        wordExpandContainer.innerText = ''
        let questionIndex = 1
        wordExpand.forEach((word) => {
            // console.log(word)
            const inputWrapper = document.createElement('p');
            const spanWrapper = document.createElement('span');
            const spanRightWrapper = document.createElement('span');
            inputWrapper.className = 'flex relative items-center gap-3 mb-3';
            spanWrapper.textContent = questionIndex + '.';
            spanRightWrapper.textContent = word
            spanWrapper.className = 'span-left'
            questionIndex++
            inputWrapper.appendChild(spanWrapper);
            inputWrapper.appendChild(spanRightWrapper);
            wordExpandContainer.appendChild(inputWrapper);
        })
        // console.log(wordArrayContainer)
    }

    //词汇-单词扩展-初始化-回答
    function wordExpandAnswerInit() {
        wordExpandAnswerContainer.innerText = ''
        let questionIndex = 1
        wordExpandQuestion.forEach((word) => {
            // console.log(word)
            const inputContainer = document.createElement('div');
            inputContainer.className = 'flex mb-3 relative items-center gap-3';

            //存放序号
            const spanWrapper = document.createElement('span');
            spanWrapper.className = 'w-6 text-center font-medium span-left';
            spanWrapper.textContent = `${questionIndex}.`;
            inputContainer.appendChild(spanWrapper);

            //存放释义
            word.forEach((meaning) => {
                const spanTextWrapper = document.createElement('span');
                spanTextWrapper.textContent = meaning;
                spanTextWrapper.className = 'text-xs'
                inputContainer.appendChild(spanTextWrapper);

                const inputWrapper = document.createElement('input');
                inputWrapper.className = 'border border-gray-300 rounded-md '
                inputWrapper.type = 'text';
                inputWrapper.placeholder = '请输入'; // 提示文本
                inputContainer.appendChild(inputWrapper);
            })

            questionIndex++
            wordExpandAnswerContainer.appendChild(inputContainer);
        })
        // console.log(wordArrayContainer)
    }

    //语法-初始化
    function grammarInputInit() {
        grammarInputContainer.innerText = grammarInputData
        grammarDemandContainer.innerText = grammarDemand.question
        document.getElementById('question_text1').innerText = grammarDemand.answer[0]
        document.getElementById('question_text2').innerText = grammarDemand.answer[1]
    }

    //文章-初始化
    function articleInputInit() {
        articleInputContainer.innerText = ''
        articleInputContainer.innerText = articleInputData
    }

    //阅读-初始化
    function readingInputInit() {
        readingInputContainer.innerText = ''
        readingInputContainer.innerText = readingInputData
    }

    //阅读-初始化
    function readingInputAnswerInit() {
        readingInputAnswerContainer.innerText = ''
        readingInputAnswer.forEach((data) => {
            // console.log(data)
            generateQuestion(data)
        })
    }

    //阅读-动态生成选择题
    function generateQuestion(questionData) {

        // 创建题干元素
        const questionElement = document.createElement('div');
        questionElement.className = 'mb-2 mt-2'
        questionElement.innerHTML = `
             ${questionData.index}. ${questionData.question}
            `;
        readingInputAnswerContainer.appendChild(questionElement);

        // 创建选项列表
        const optionsList = document.createElement('div');
        optionsList.className = 'space-y-1';

        // 生成每个选项
        questionData.answer.forEach((option, index) => {
            const optionElement = document.createElement('div');
            optionElement.className = 'option border-gray-200 rounded-lg';
            optionElement.dataset.id = 'option-' + questionData.index;
            optionElement.innerHTML = `
                    <div class="flex items-center">
                        <span class="w-4 h-4 rounded-full border-2 border-gray-300 flex items-center justify-center mr-3 flex-shrink-0">
                            ${String.fromCharCode(65 + index)}
                        </span>
                        <span>${option}</span>
                    </div>
                `;

            const questionId = 'option-' + questionData.index
            // console.log(questionData.index)

            // 给选项添加点击事件
            optionElement.addEventListener('click', (index) => {
                console.log(index);
                // 清除其他选项的选中状态
                document.querySelectorAll(`[data-id="${questionId}"]`).forEach(opt => {
                    opt.classList.remove('selected');
                });

                // 设置当前选项为选中状态
                optionElement.classList.add('selected');
                // selectedAnswer = index;
            });

            optionsList.appendChild(optionElement);
        });

        readingInputAnswerContainer.appendChild(optionsList);
    }

    //语法-初始化
    function grammarInputAnswerInit() {
        grammarInputAnswerContainer.innerText = ''
        let questionIndex = 1
        grammarInputAnswer.forEach((grammarAnswer) => {
            const inputContainer = document.createElement('div');
            inputContainer.className = 'flex mb-3 relative items-center gap-5';
            const inputWrapper = document.createElement('input');
            const spanWrapper = document.createElement('span');
            spanWrapper.className = 'w-6 text-center font-medium span-left'; // 固定宽度，居中对齐
            spanWrapper.textContent = `${questionIndex}.`;
            inputWrapper.placeholder = `请输入第 ${questionIndex} 个`;
            inputWrapper.type = 'text';
            inputWrapper.className = 'w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500';

            questionIndex++
            inputContainer.appendChild(spanWrapper);
            inputContainer.appendChild(inputWrapper);
            grammarInputAnswerContainer.appendChild(inputContainer);
        })
    }

    // 计时器功能
    function startTimer() {
        let minutes = 35
        let seconds = 0;
        const timerElement = document.getElementById('timer');

        const interval = setInterval(() => {
            // 更新显示
            timerElement.textContent = `${minutes.toString().padStart(2, '0')}:${seconds.toString().padStart(2, '0')}`;

            // 时间减少
            if (seconds === 0) {
                if (minutes === 0) {
                    clearInterval(interval);
                    // 时间到自动提交
                    document.getElementById('submitBtn').click();
                    return;
                }
                minutes--;
                seconds = 59;
            } else {
                seconds--;
            }

            // 剩余5分钟时警告
            if (minutes < 5) {
                timerElement.classList.add('text-danger', 'animate-pulse');
            }
        }, 1000);
    }

    // 交卷功能
    const submitBtn = document.getElementById('submitBtn');
    const submitModal = document.getElementById('submitModal');
    const cancelSubmit = document.getElementById('cancelSubmit');
    const confirmSubmit = document.getElementById('confirmSubmit');
    const successModal = document.getElementById('successModal');
    const closeSuccess = document.getElementById('closeSuccess');

    submitBtn.addEventListener('click', () => {
        submitModal.classList.remove('hidden');
        // successModal.classList.remove('hidden');
    });

    cancelSubmit.addEventListener('click', () => {
        submitModal.classList.add('hidden');
    });

    confirmSubmit.addEventListener('click', () => {
        let check = getUserInputData()
        if (check) {
            getSubmitResultAll()
            submitModal.classList.add('hidden');
            successModal.classList.remove('hidden');
            initCollectCollections()
            // console.log(userData);
            submitData()
        } else {
            submitModal.classList.add('hidden');
        }
    });

    closeSuccess.addEventListener('click', () => {
        successModal.classList.add('hidden');

        document.querySelectorAll('.popup-container-hidden').forEach(item => {
            item.style.display = 'block';
        })
        //location.reload(); // 普通刷新（可能从缓存加载）
    });

    function getSubmitResult(id, rate, correct) {
        let elementById = document.getElementById(id);
        let num = id.substring(id.length - 1);
        let title = ''
        if (parseInt(num) === 2) {
            title = '听力-短文:'
        } else if (parseInt(num) === 3) {
            title = '阅读:'
        } else if (parseInt(num) === 1) {
            title = '语法-语句:'
        } else if (parseInt(num) === 5) {
            title = '词汇:'
        } else if (parseInt(num) === 6) {
            title = '语法-单词:'
        }
        elementById.innerHTML = title + "-正确个数:" + correct + "-正确率:" + rate + "%"
    }

    function initCollectCollections() {
        correctCollections = {}
    }

    function getSubmitResultAll() {
        //语法-语句-✅
        getSubmitResult("submitData1", correctCollections.correct1, correctCollections.num1 + '/5')
        //语法-单词-✅
        getSubmitResult("submitData6", correctCollections.correct6, correctCollections.num6 + '/10')
        //听力-短文-✅
        getSubmitResult("submitData2", correctCollections.correct2, correctCollections.num2 + '/5')
        //听力-选择-✅
        getSubmitResult("submitData7", correctCollections.correct7, correctCollections.num7 + '/5')
        //阅读-✅
        getSubmitResult("submitData3", correctCollections.correct3, correctCollections.num3 + '/6')
        //听力-单词-✅
        getSubmitResult("submitData4", correctCollections.correct4, correctCollections.num4 + '/10')
        //词汇-✅
        getSubmitResult("submitData5", correctCollections.correct5, correctCollections.num5 + '/20')
    }

    //提交数据到服务器
    function submitData() {
        // console.log(JSON.stringify(userData))
        // 发送 POST 请求
        fetch('http://1.92.74.42:8088/comprehensive/exam', {
            method: 'POST', // 指定 POST 方法
            headers: {
                'Content-Type': 'application/json', // 声明数据格式为 JSON
                // 可添加其他请求头，如认证信息
                // 'Authorization': 'Bearer token123'
            },
            body: JSON.stringify(userData) // 将数据转为 JSON 字符串
        }).then(response => {
            if (!response.ok) {
                throw new Error('提交失败');
            }
            return response.json(); // 解析后端返回的 JSON 响应
        }).then(() => {
            userData = {}
            selectQuestionValueList = []
        }).catch(() => {
            alert('提交失败，请重试');
        });
    }

    //判断用户输入是否完整
    function getUserInputData() {
        let name = document.getElementById('name').value;
        let campus = document.getElementById('campus').value;
        if (name === null || name === '') {
            alert('Please enter your name');
            return false;
        }
        if (campus === null || campus === '') {
            alert('Please enter your campus');
            return false;
        }
        userData.name = name;
        userData.campus = campus;
        userData.typeName = '挑战版';
        getUserAllInputData()
        return true;
    }

    //获取到用户的所有输入
    function getUserAllInputData() {
        //听力
        getUserListenAnswerWord('wordListenDataContainer', 'word listen and input')
        getUserListenAnswerData('inputContainer', 'Events during Kenton Festival')
        //语法-单词
        getUserInputGrammarWord()
        //阅读
        getUserReadingSelectData()
        //写作
        getUserAnswerData('article', 'article', 30)
    }

    function test() {

    }

    //语法-单词
    function getUserInputGrammarWord() {
        //记录正确率
        correctCollections.num6 = 0
        let correctArray = []
        for (let i = 0; i < grammarWordContext.length; i++) {
            correctArray.push(grammarWordContext[i]['correct'])
        }
        // console.log(grammarWordShuffle);
        Object.values(grammarSelectAnswers).forEach(item => {
            if (correctArray.indexOf(item) !== -1) {
                correctCollections.num6++
            }
        })
        correctCollections.correct6 = parseInt((correctCollections.num6 * 10).toString());

        //保存用户数据
        Object.keys(grammarSelectAnswers).forEach(key => {
            // console.log(key + '--'+ grammarSelectAnswers[key] + '--'+ grammarWordShuffle[key - 1]['correct']);
            const inputInfo = {
                questionsNumber: key,
                correctText: '', //
                correctAnswer: grammarWordShuffle[key - 1]['correct'],
                score: 2,
                userText: '',
                userAnswer: grammarSelectAnswers[key],
                questionsText: grammarWordShuffle[key - 1]['title']
            };
            userData.list.push(inputInfo);
        })
        // console.log(correctCollections.num6);
    }

    //阅读-选择
    function getUserReadingSelectData() {
        let data = userReadingSelect
        // console.log(data)
        if (data.length === 0) {
            return
        }
        const keys = Object.keys(data);
        let correct = 0
        for (let i = 0; i < keys.length; i++) {
            const key = keys[i];
            let item = {
                questionsNumber: i + 1,
                score: 5,
                correctAnswer: readingCorrect[i], //
                userText: '',
                userAnswer: parseInt(userReadingSelect[key]),
                questionsText: 'List of Headings'
            };
            userData.list.push(item);
            if (item.correctAnswer === item.userAnswer) {
                correct++;
            }
        }
        correctCollections.num3 = correct
    }

    //写作
    function getUserAnswerData(id, title, score) {
        let paraphraseContent = document.getElementById(id).value
        let item = {
            questionsNumber: 1,
            score: score,
            correctAnswer: 0, //
            userAnswer: 0, //
            userText: paraphraseContent,
            questionsText: title
        };
        if (item.userText !== '') {
            userData.list.push(item);
        }
    }

    //听力-短文
    function getUserListenAnswerData(id, title) {
        let inputGroup = document.getElementById(id)

        //选择 div 内所有 input（返回 NodeList 集合）
        const inputs = inputGroup.querySelectorAll('input', '.paraphraseInput');
        let correctNum = 0

        //遍历集合，收集值（支持 forEach/for 循环）
        inputs.forEach((input, index) => {
            // 获取 input 的关键信息：类型、占位符、输入值
            const inputInfo = {
                questionsNumber: index + 1,          // 序号（从1开始）
                correctText: input.correctText, //
                correctAnswer: 0,
                score: 2,
                userText: input.value.trim(),  // 输入值（去空格）
                questionsText: title
            };
            if (inputInfo.correctText.indexOf('/') === -1) {
                if (inputInfo.correctText.toLowerCase() === inputInfo.userText.toLowerCase()) {
                    correctNum++;
                }
            } else {
                let correctArrays = inputInfo.correctText.split('/');
                if (correctArrays.includes(inputInfo.userText.toLowerCase())) {
                    correctNum++;
                }
            }
            if (inputInfo.userText !== '') {
                userData.list.push(inputInfo);
            }
        });
        // console.log(userData.list)
        correctCollections.num2 = correctNum
        correctCollections.correct2 = parseInt((correctNum * 100 / inputs.length).toString());
    }

    //听力-单词
    function getUserListenAnswerWord(id, title) {
        let inputGroup = document.getElementById(id)

        // 2.1 选择 div 内所有 input（返回 NodeList 集合）
        const inputs = inputGroup.querySelectorAll('input', '.wordInput');
        // console.log(inputs.length)

        // 2.2 遍历集合，收集值（支持 forEach/for 循环）
        inputs.forEach((input, index) => {
            // 获取 input 的关键信息：类型、占位符、输入值
            const inputInfo = {
                questionsNumber: index + 1,          // 序号（从1开始）
                correctText: input.correctText, //
                correctAnswer: 0,
                score: 2,
                userText: input.value.trim(),  // 输入值（去空格）
                questionsText: title
            };
            // console.log(inputInfo);
            if (inputInfo.correctText.indexOf('/') === -1) {
                if (inputInfo.correctText.toLowerCase() === inputInfo.userText.toLowerCase()) {
                    correctCollections.num4++;
                }
            } else {
                let correctArrays = inputInfo.correctText.split('/');
                if (correctArrays.includes(inputInfo.userText.toLowerCase())) {
                    correctCollections.num4++;
                }
            }
            if (inputInfo.userText !== '') {
                userData.list.push(inputInfo);
            }
        });

        correctCollections.correct4 = parseInt((correctCollections.num4 * 10).toString());
    }

    //语法-句子
    document.querySelectorAll('input[name^="select"]').forEach(radio => {
        radio.addEventListener('change', function () {
            let selectedValue = getSelectedValue(this.name);
            let number = this.name.toString().substring(6);
            const inputInfo = {
                questionsNumber: number,          // 序号（从1开始）
                correctText: '', //
                correctAnswer: grammarSentenceCorrect[number - 1],
                score: 5,
                userText: '',
                userAnswer: selectedValue,
                questionsText: this.name
            };

            if (selectQuestionValueList.indexOf(this.name) === -1) {
                selectQuestionValueList.push(this.name);
                userData.list.push(inputInfo);
                if (inputInfo.correctAnswer === parseInt(inputInfo.userAnswer)) {
                    correctCollections.num1++;
                }
            } else {
                userData.list = userData.list.filter(item => item.questionsText !== this.name);
                userData.list.push(inputInfo);
            }

            correctCollections.correct1 = parseInt((correctCollections.num1 * 20).toString());
            // console.log(userData.list);
        });
    });

    //听力-选择
    document.querySelectorAll('input[name^="listen_select"]').forEach(radio => {
        radio.addEventListener('change', function () {
            let selectedValue = getSelectedValue(this.name);
            let number = this.name.toString().substring(13);
            const inputInfo = {
                questionsNumber: number,          // 序号（从1开始）
                correctText: '', //
                correctAnswer: listenSelectContext[number - 1],
                score: 2,
                userText: '',
                userAnswer: selectedValue,
                questionsText: this.name
            };

            if (selectQuestionValueList.indexOf(this.name) === -1) {
                selectQuestionValueList.push(this.name);
                userData.list.push(inputInfo);
                if (inputInfo.correctAnswer === parseInt(inputInfo.userAnswer)) {
                    correctCollections.num7++;
                }
            } else {
                userData.list = userData.list.filter(item => item.questionsText !== this.name);
                userData.list.push(inputInfo);
            }

            correctCollections.correct7 = parseInt((correctCollections.num7 * 20).toString());
            // console.log(userData.list);
        });
    });

    //检查与判卷
    document.querySelectorAll('.popup-container-hidden').forEach(item => {
        item.style.display = 'none';
    })

    // 方法：根据name属性获取选中的值
    function getSelectedValue(name) {
        // 关键：通过模板字符串将参数拼接到选择器中
        const selected = document.querySelector(`input[name="${name}"]:checked`);
        return selected ? selected.value : "none";
    }

    // 页面加载完成后启动计时器
    window.addEventListener('DOMContentLoaded', () => {
        wordTranslateInit()
        wordTranslateAnswerInit()

        wordExpandInit();
        wordExpandAnswerInit();

        grammarInputInit();
        grammarInputAnswerInit();

        articleInputInit();

        readingInputInit();
        readingInputAnswerInit();

        startTimer();
    });
</script>
</body>
</html>
